import axios from 'axios';

/**
 * @type {import('vuex').Module}
 */
const list = {
  namespaced: true,
  state: {
    list: [],
    type: 'all',
  },
  mutations: {
    updateList(state, payLoad) {
      state.list = payLoad
    },
    delList(state, id) {
      state.list = state.list.filter(item => item.id !== id)
    },
    addList(state, data) {
      state.list.unshift(data)
    },
    changeIsDone(state, data) { 
      state.list.find(item => item.id === data.id).isDone = data.isDone
    },
    changeType(state, type) {
			state.type = type
		},
  },
  actions: {
    async getList(context) {
      const res = await axios({
        method: 'get',
        url: 'http://localhost:3000/list'
      })
      // console.log(res);
      context.commit('updateList', res.data)
    },
    async del(context, id) {
      await axios({
        method: 'delete',
        url: 'http://localhost:3000/list/' + id,
      })
      context.commit('delList', id)
    },
    async add(context, data) {
      await axios({
        method: 'post',
        url: 'http://localhost:3000/list/',
        data,
      })
      context.commit('addList', data)
    },
    async isDone(context, data) {
      await axios({
        method: 'patch',
        url: 'http://localhost:3000/list/'+data.id,
        data,
      })
      context.commit('changeIsDone', data)
    },
  },
  getters: {
    showList (state) {
      if (state.type === 'completed') { 
        return state.list.filter(item => item.isDone === true)
      } else if (state.type === 'active') {
        return state.list.filter(item => item.isDone === false)
      } else {
        return state.list 
      }
    }
  }
}
export default list
